<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Db;

use app\index\model\User as UserModel;

class Index extends Controller
{
	public function index(){
		// 获取用户信息 $indexUserInfo['indexUserInfo']
        $indexUserInfo = Session::get('indexUserInfo');
        if ($indexUserInfo == null) {
            $this->redirect('/index/index/login.html');
        }
		return $this->fetch();  
	}
	
	/**
	 * 获取评教数据列表
	 */
    public function infoList()
    {
    	// 获取用户信息 $indexUserInfo['indexUserInfo']
        $indexUserInfo = Session::get('indexUserInfo');
        if ($indexUserInfo == null) {
            $this->redirect('/index/index/login.html');
        }
       
        // 查询所有老师关联信息
        $getCCTSql = "
        	SELECT 
			DISTINCT(course.`name`) as 'coursename',
			course.courseimg AS 'courseimg',
			teacher.`id` AS 'teacherid',
			teacher.`name` AS 'teachername',
			teacher.`sex` AS 'teachersex'
			FROM((
				oes_emp teacher  LEFT JOIN  oes_dept dept ON teacher.dept_id = dept.id
			)	LEFT JOIN oes_clazzcourseteacher ccse ON ccse.teacher_id = teacher.id
			) LEFT JOIN oes_course course ON course.id = ccse.course_id
			WHERE teacher.dept_id = ?
        	";
        if($indexUserInfo['type'] == 2){
        	 // 查询班级、课程、老师关联信息
	        $getCCTSql = "
	        	SELECT 
					class.`name` AS 'classname',
					course.`name` as 'coursename',
					course.courseimg AS 'courseimg',
					teacher.`id` AS 'teacherid',
					teacher.`name` AS 'teachername',
					teacher.`sex` AS 'teachersex'
				FROM(((
					  oes_clazzcourseteacher ccse LEFT JOIN oes_clazz class ON class.id = ccse.clazz_id
					) LEFT JOIN oes_course course ON course.id = ccse.course_id
					) LEFT JOIN oes_emp teacher ON teacher.id = ccse.teacher_id
					) LEFT JOIN oes_student student ON student.clazz_id = ccse.clazz_id
					  WHERE teacher.`status` = 1 AND class.`code` = ? AND student.sysuser_id = ?
	        	";
        }	
        
		//查询某个老师被评人次数
		$getPJCountSql = "
			SELECT
				COUNT(erecord.id) AS 'count'
			FROM oes_erecordnew erecord LEFT JOIN oes_etask etask ON etask.id = erecord.etask_id
				WHERE erecord.teacher_id = ? AND erecord.etask_id = ?
			";
			
		$getEtaskSql = "
			SELECT 
				*
			FROM 
				oes_etask
			WHERE 
				end_data > date_format(now(),'%y-%m-%d') AND status = 1
		";
		
		if($indexUserInfo['type'] == 2){
		 	 $getCCT = Db::query($getCCTSql, [$indexUserInfo['classcode'],$indexUserInfo['sysuser_id']]);
		}else{
			 $getCCT = Db::query($getCCTSql, [$indexUserInfo['dept_id']]);
		}
       
		$getEtask = Db::query($getEtaskSql);
		
		if(count($getEtask) > 0 ){
			foreach ($getCCT as &$item) {
            // dump($item['id']);
	           $getPJCount = Db::query($getPJCountSql,[$item['teacherid'],$getEtask[0]['id']]);
	           //dump($getPJCount);
	           $item['getPJCount'] = $getPJCount[0]['count'];
	           $item['startData'] = $getEtask[0]['start_data'];
	           $item['endData'] = $getEtask[0]['end_data'];
	        }
		}else{
			return json(['success'=>false, "msg"=>'当前没有评教任务哦']);
		}
		
	/*	
		dump($getCCT);*/
        //$this->assign("list", $getCCT);	
		//dump(json(['success'=>true, "msg"=>'OK','obj'=>$getCCT]));
		return json(['success'=>true, "msg"=>'OK','obj'=>$getCCT]);
         	
    }
    
    public function getInfoList(){
    	// 获取用户信息 $indexUserInfo['indexUserInfo']
        $indexUserInfo = Session::get('indexUserInfo');
        if ($indexUserInfo == null) {
            $this->redirect('/index/index/login.html');
        }
		
		 // 查询所有老师关联信息
        $getCCTSql = "
        	SELECT 
			DISTINCT(course.`name`) as 'coursename',
			course.courseimg AS 'courseimg',
			teacher.`id` AS 'teacherid',
			teacher.`name` AS 'teachername',
			teacher.`sex` AS 'teachersex'
			FROM((
				oes_emp teacher  LEFT JOIN  oes_dept dept ON teacher.dept_id = dept.id
			)	LEFT JOIN oes_clazzcourseteacher ccse ON ccse.teacher_id = teacher.id
			) LEFT JOIN oes_course course ON course.id = ccse.course_id
			WHERE teacher.dept_id = ? AND (teacher.`name` LIKE ? OR course.`name` LIKE ?) 
        	";
        if($indexUserInfo['type'] == 2){
        	 // 查询班级、课程、老师关联信息
	        $getCCTSql = "
	        	SELECT 
					class.`name` AS 'classname',
					course.`name` as 'coursename',
					course.courseimg AS 'courseimg',
					teacher.`id` AS 'teacherid',
					teacher.`name` AS 'teachername',
					teacher.`sex` AS 'teachersex'
				FROM(((
					  oes_clazzcourseteacher ccse LEFT JOIN oes_clazz class ON class.id = ccse.clazz_id
					) LEFT JOIN oes_course course ON course.id = ccse.course_id
					) LEFT JOIN oes_emp teacher ON teacher.id = ccse.teacher_id
					) LEFT JOIN oes_student student ON student.clazz_id = ccse.clazz_id
				WHERE 
					teacher.`status` = 1 AND class.`code` = ? AND student.sysuser_id = ? AND (teacher.`name` LIKE ? OR course.`name` LIKE ?) 
	        	";
        }	
    	 // 查询班级、课程、老师关联信息
       
		//查询某个老师被评人次数
		$getPJCountSql = "
			SELECT
				COUNT(erecord.id) AS 'count'
			FROM oes_erecordnew erecord LEFT JOIN oes_etask etask ON etask.id = erecord.etask_id
				WHERE erecord.teacher_id = ? AND erecord.etask_id = ?
			";
			
		$getEtaskSql = "
			SELECT 
				*
			FROM 
				oes_etask
			WHERE 
				end_data > date_format(now(),'%y-%m-%d')
		";
		
		$sousuo = "%".$_POST['sousuo']."%";
        if($indexUserInfo['type'] == 2){
		 	$getCCT = Db::query($getCCTSql, [$indexUserInfo['classcode'],$indexUserInfo['sysuser_id'],$sousuo,$sousuo]);
		
		}else{
			$getCCT = Db::query($getCCTSql, [$indexUserInfo['dept_id'],$sousuo,$sousuo]);
		}
      
		$getEtask = Db::query($getEtaskSql);
		if(count($getCCT) > 0 ){
			foreach ($getCCT as &$item) {
	            // $SubMenu = Db::query($subMenuSql, [2, $item]);
	            // dump($item['id']);
	           $getPJCount = Db::query($getPJCountSql,[$item['teacherid'],$getEtask[0]['id']]);
	           $item['getPJCount'] = $getPJCount[0]['count'];
	           $item['startData'] = $getEtask[0]['start_data'];
	           $item['endData'] = $getEtask[0]['end_data'];
	        }
	        return json(['success'=>true, "msg"=>'OK', "code"=>1,'obj'=>$getCCT]);
		}else{
			return json(['success'=>true, "msg"=>'没有数据哦！请重新设置搜索条件吧', "code"=>0,'obj'=>count($getCCT)]);
		}
		
	/*	dump($getEtask);
		dump($getCCT);*/
        //$this->assign("list", $getCCT);	
		//dump(json(['success'=>true, "msg"=>'OK','obj'=>$getCCT]));
		
    }

	//登录页面跳转控制器
	public  function login(){
	  return $this->fetch("common/login");//对应index/view/common/login.html	
	}
	
	public function loginOut(){
		Session::set('indexUserInfo', null);
		return $this->fetch("common/login");//对应index/view/common/login.html	
	}
	
	//注册页面跳转控制器
	public  function reg(){
	  return $this->fetch("common/reg");//对应index/view/common/login.html	
	}
	
	 /**
     * 登陆提交
     * @param Request $request
     * @return \think\response\Json
     */
    public function loginPost(Request $request) {
        // 获取参数仅包含数组中字段
        $data = $request->only(['username', 'password']);
        if ($data == null) {
            return json(['success'=>false, "msg"=>'账号或密码输入有误']);
        }
		$data['password'] = MD5($data['password'].'OES');
        $userInfo = Db::table('user')->where($data)->find();
        if ($userInfo!=null) {
            $getUserInfoSql = "
				SELECT 
					student.*,
					class.`code` AS 'classcode',
					dept.`name` AS 'deptname'
				FROM(
					oes_student student LEFT JOIN oes_clazz class ON class.id = student.clazz_id
				) LEFT JOIN oes_dept dept ON dept.id = student.dept_id
				  WHERE student.sysuser_id = ?
				";
				
			$getUserErecordSql = "
				SELECT
					COUNT(erecord.id) AS 'count'
				FROM 
					oes_erecordnew erecord LEFT JOIN oes_etask etask ON etask.id = erecord.etask_id
				WHERE 
					erecord.euser_id = ?
			";
			
			$getUserBErecordSql = "
				SELECT
					COUNT(erecord.id) AS 'count'
				FROM 
					oes_erecordnew erecord LEFT JOIN oes_etask etask ON etask.id = erecord.etask_id
				WHERE 
					erecord.teacher_id = ?
			";
			
			if($userInfo['type'] !=2){//查当前登录用户不为学生的基本信息
				$getUserInfoSql = "
					SELECT 
						teacher.*,
						dept.`name` AS 'classcode'
					FROM
						oes_emp teacher LEFT JOIN oes_dept dept ON dept.id = teacher.dept_id
						WHERE teacher.sysuser_id = ?
					";
			}
					
			$indexUserInfo = Db::query($getUserInfoSql, [$userInfo['id']]);
			
			if($userInfo['type'] == 1){
				$empInfo = Db::table('oes_emp')->where('sysuser_id = '.$userInfo['id'])->find();
				$getUserBErecord = Db::query($getUserBErecordSql, [$empInfo['id']]);
				//个人被评教次数
				$indexUserInfo[0]['userberecord'] = $getUserBErecord[0]['count'];
			}
			$getUserErecord = Db::query($getUserErecordSql, [$userInfo['id']]);
			
			
			$indexUserInfo[0]['type'] = $userInfo['type'];
			$indexUserInfo[0]['username'] = $data['username'];
			//个人评教次数
			$indexUserInfo[0]['usererecord'] = $getUserErecord[0]['count'];
			//dump($indexUserInfo[0]['usererecord']);
			
			
            Session::set('indexUserInfo', $indexUserInfo[0]);

        	return json(['success'=>true, "msg"=>'登录成功', 'obj'=>$indexUserInfo[0]]);
        } else {
            return json(['success'=>false, "msg"=>'账号或密码错误']);
        }
    }

	/**
     * 注册提交
     * @param Request $request
     * @return \think\response\Json
     */
    public function regPost(Request $request) {
        // 获取参数仅包含数组中字段
        $data = $request->only(['username', 'password']);
        if ($data == null) {
            return json(['success'=>false, "msg"=>'账号或密码输入有误']);
        }
      	$data['password'] = MD5($data['password'].'OES');
		$data['nickname'] = $data['username'];
		$data['type'] = 2;
		$data['status'] = 1;
		$data['gmt_create'] = date('y-m-d h:i:s',time());
		$data['gmt_modified'] = $data['gmt_create'];
	
		$User = new UserModel();//创建模型
		// 启动事务
		$User->startTrans();
		try{
		    $data1['sysuser_id'] = $User->insertGetId($data);
		    if($data1['sysuser_id'] > 0){
				$result = Db::table('oes_student')->insert($data1);
				if($result>0){
					// 提交事务
		    		$User->commit();  
					
					$getUserInfoSql = "
						SELECT 
							student.*,
							class.`code` AS 'classcode',
							dept.`name` AS 'deptname'
						FROM(
							oes_student student LEFT JOIN oes_clazz class ON class.id = student.clazz_id
						) LEFT JOIN oes_dept dept ON dept.id = student.dept_id
						  WHERE student.sysuser_id = ?
						";
						
					$getUserErecordSql = "
						SELECT
							COUNT(erecord.id) AS 'count'
						FROM 
							oes_erecordnew erecord LEFT JOIN oes_etask etask ON etask.id = erecord.etask_id
						WHERE 
							erecord.euser_id = ?
					";
					
					
					$indexUserInfo = Db::query($getUserInfoSql, [$data1['sysuser_id']]);
					$getUserErecord = Db::query($getUserErecordSql, [$data1['sysuser_id']]);
					
					
					$indexUserInfo[0]['type'] = 2;
					$indexUserInfo[0]['username'] = $data['username'];
					//个人评教次数
					$indexUserInfo[0]['usererecord'] = $getUserErecord[0]['count'];
					Session::set('indexUserInfo', $indexUserInfo[0]);
	
		        	return json(['success'=>true, "msg"=>'注册成功', 'obj'=>$indexUserInfo[0]]);
				}else{
					 // 回滚事务
					$User->rollback();
					return json(['success'=>false, "msg"=>'网络错误']);
				}
			}
		   
		} catch (\Exception $e) {
		    // 回滚事务
		   $User->rollback();
		   return json(['success'=>false, "msg"=>'网络错误']);
		}
	  
    }
	
	
}
